<template>
  <div class="productManager">
    <div class="breadcrumb">
      <el-icon>
        <Location />
      </el-icon>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>产品管理</el-breadcrumb-item>
        <el-breadcrumb-item>产品列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="产品列表" name="first">
        <div class="content">
          <div class="top">
            <div style="display:flex;">
              <el-input
                v-model="product_id"
                class="w-50 m-2"
                placeholder="请输入入库编号进行搜索"
                :prefix-icon="Search"
              ></el-input>
              <el-button type="primary" @click="togetProduct()">确认</el-button>
            </div>
            <div>
              <el-button type="primary" @click="dialogVisible = true; isEdit = false;">添加产品</el-button>
            </div>
          </div>

          <el-table :data="tableData" border style="width: 100%">
            <el-table-column show-overflow-tooltip type="index" width="50" />
            <el-table-column show-overflow-tooltip prop="product_id" label="入库编号" />
            <el-table-column show-overflow-tooltip prop="product_name" label="产品名称" />
            <el-table-column show-overflow-tooltip prop="product_category" label="产品类别" />
            <el-table-column show-overflow-tooltip prop="product_unit" label="产品单位" />
            <el-table-column show-overflow-tooltip prop="product_inwarehouse_number" label="库存数量" />
            <el-table-column show-overflow-tooltip prop="product_single_price" label="产品单价" />
            <el-table-column show-overflow-tooltip prop="product_all_price" label="库存总价" />
            <el-table-column show-overflow-tooltip prop="product_status" label="库存状态">
              <template #default="scope">
                <el-tag v-if="scope.row.product_inwarehouse_number < 100" type="danger">告急</el-tag>
                <el-tag
                  v-else-if="scope.row.product_inwarehouse_number >= 100 && scope.row.product_inwarehouse_number <= 300"
                  type="success"
                >正常</el-tag>
                <el-tag v-else>过剩</el-tag>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="product_create_person" label="入库操作人" />
            <el-table-column
              show-overflow-tooltip
              prop="product_create_time"
              label="入库时间"
              width="200px"
            />
            <el-table-column
              show-overflow-tooltip
              prop="product_update_time"
              label="产品最新跟新时间"
              width="200px"
            />
            <el-table-column show-overflow-tooltip prop="in_memo" label="入库备注" />
            <el-table-column show-overflow-tooltip label="操作" width="220">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  @click="handleOutbound(scope.$index, scope.row)"
                  :disabled="scope.row.product_out_status == '申请出库'"
                >申请出库</el-button>
                <el-button
                  size="small"
                  type="success"
                  @click="handleEdit(scope.$index, scope.row)"
                  :disabled="scope.row.product_out_status == '申请出库'"
                >编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                  :disabled="scope.row.product_out_status == '申请出库'"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="pageNum"
            :page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane label="审核列表" name="second">
        <div class="content">
          <div class="top">
            <div style="display:flex;">
              <el-input
                v-model="product_out_id"
                class="w-50 m-2"
                placeholder="请输入入库编号进行搜索"
                :prefix-icon="Search"
              ></el-input>
              <el-button type="primary" @click="togetApplyProduct()">确认</el-button>
            </div>
            <!-- <div>
              <el-button type="primary" @click="dialogVisible = true; isEdit = false;">添加产品</el-button>
            </div>-->
          </div>

          <el-table :data="tableDataExamine" border style="width: 100%">
            <el-table-column show-overflow-tooltip type="index" width="50" />
            <el-table-column show-overflow-tooltip prop="product_out_id" label="出库编号" />
            <el-table-column show-overflow-tooltip prop="product_name" label="产品名称" />
            <el-table-column show-overflow-tooltip prop="product_out_number" label="出库数量" />
            <el-table-column show-overflow-tooltip prop="product_out_price" label="出库价格" />
            <el-table-column show-overflow-tooltip prop="product_out_apply_person" label="出库申请人" />
            <el-table-column show-overflow-tooltip prop="product_aut_audit_person" label="审核人" />
            <el-table-column show-overflow-tooltip prop="product_out_status" label="审核状态" />
            <el-table-column
              show-overflow-tooltip
              prop="product_out_apply_date"
              label="申请出库时间"
              width="200px"
            />
            <el-table-column show-overflow-tooltip prop="apply_memo" label="申请出库备注" />
            <el-table-column show-overflow-tooltip prop="audit_memo" label="审核备注" />

            <el-table-column show-overflow-tooltip label="操作" width="170">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  @click="handleWithdraw(scope.$index, scope.row)"
                >撤回申请</el-button>
                <el-button
                  size="small"
                  type="success"
                  @click="handleExamine(scope.$index, scope.row)"
                >审核</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="pageNum1"
            :page-size="pageSize1"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalExamine"
            @size-change="handleSizeChange1"
            @current-change="handleCurrentChange1"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      draggable
      v-model="dialogVisible"
      :title="(isEdit ? '修改' : '新建') + '产品'"
      width="30%"
      @close="dialogVisibleClose(ruleFormRef)"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="入库编号" prop="product_id">
          <el-input v-model="ruleForm.product_id" :disabled="isEdit" placeholder="入库编号" />
        </el-form-item>
        <el-form-item label="产品名称" prop="product_name">
          <el-input v-model="ruleForm.product_name" placeholder="产品名称" />
        </el-form-item>
        <el-form-item label="产品类别" prop="product_category">
          <el-select v-model="ruleForm.product_category" placeholder="产品类别" style="width:100%">
            <el-option
              :label="item.name"
              :value="item.name"
              v-for="item in dynamicTags1"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品单位" prop="product_unit">
          <el-select v-model="ruleForm.product_unit" placeholder="产品单位" style="width:100%">
            <el-option label="个" value="个" />
            <el-option label="件" value="件" />
            <el-option label="元" value="元" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存数量" prop="product_inwarehouse_number">
          <el-input-number
            v-model="ruleForm.product_inwarehouse_number"
            controls-position="right"
            :min="1"
            placeholder="库存数量"
          />
        </el-form-item>
        <el-form-item label="产品单价" prop="product_single_price">
          <el-input v-model="ruleForm.product_single_price" placeholder="产品单价" />
        </el-form-item>
        <el-form-item label="入库操作人" prop="product_create_person">
          <el-input
            v-model="ruleForm.product_create_person"
            :disabled="isEdit"
            placeholder="入库操作人"
          />
        </el-form-item>
        <el-form-item label="入库备注" prop="in_memo">
          <el-input type="textarea" v-model="ruleForm.in_memo" placeholder="入库备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      draggable
      v-model="outboundDialogVisible"
      title="申请出库"
      width="30%"
      @close="outbounddialogVisibleClose(outboundFormRef)"
    >
      <div style="margin-bottom:10px;">申请出库的产品是： {{outboundForm.product_name }}</div>
      <el-form
        ref="outboundFormRef"
        :model="outboundForm"
        :rules="outboundRules"
        label-width="120px"
        status-icon
      >
        <el-form-item label="出库编号" prop="product_out_id">
          <el-input v-model="outboundForm.product_out_id" placeholder="出库编号" />
        </el-form-item>
        <el-form-item label="出库数量" prop="product_out_number">
          <el-input-number v-model="outboundForm.product_out_number" controls-position="right" :min="1" :max="rowInfo.product_inwarehouse_number" placeholder="出库数量" />
   
            
            
            
   
   

        </el-form-item>
        <el-form-item label="出库价格" prop="product_out_price">
          <el-input v-model="outboundForm.product_out_price" placeholder="出库价格" />
        </el-form-item>
        <el-form-item label="出库申请人" prop="product_out_apply_person">
          <el-input v-model="outboundForm.product_out_apply_person" placeholder="出库申请人" />
        </el-form-item>

        <el-form-item label="申请备注" prop="apply_memo">
          <el-input type="textarea" v-model="outboundForm.apply_memo" placeholder="申请备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="outboundDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitOutbound(outboundFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      draggable
      v-model="examineDialogVisible"
      title="审核产品"
      width="30%"
      @close="examineDialogVisibleClose"
    >
      <el-form
        ref="examineFormRef"
        :model="examineForm"
        :rules="examineRules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
        label-position="top"
      >
        <el-form-item label="确定审核此产品的出库吗？" prop="product_out_status">
          <el-radio-group v-model="outboundForm.product_out_status">
            <el-radio label="同意">同意</el-radio>
            <el-radio label="禁止">禁止</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核人" prop="product_out_audit_person">
          <el-input v-model="outboundForm.product_out_audit_person" placeholder="审核人" />
        </el-form-item>
        <el-form-item label="审核备注" prop="audit_memo">
          <el-input type="textarea" v-model="outboundForm.audit_memo" placeholder="审核备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="examineDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="toauditProduct()">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import {
  addProduct, //添加产品
  getProduct, //获取产品
  editProduct, // 修改产品
  deleteProduct,
  getApplyProduct, // 获取产品审核列表
  applyProduct, // 申请出库
  auditProduct, // 审核产品
  withdraw
} from "@/api/product";
import { addOperationLog } from "@/api/log";

import { getProductType } from "@/api/user";
import { useRouter } from "vue-router";
const router = useRouter();

// 调用store树中内容需要引入
import { useStore } from "vuex";
// 获取store
const store = useStore();

import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  House,
  Message,
  Grid,
  Avatar,
  Position,
  ChatLineSquare,
  Notebook,
  UserFilled,
  User,
  Notification,
  ChatRound
} from "@element-plus/icons-vue";

const activeName = ref("first");

const dialogVisible = ref(false);
const ruleFormRef = ref();
const ruleForm = reactive({
  id: "",
  product_id: "",
  product_name: "",
  product_category: "",
  product_unit: "",
  product_inwarehouse_number: "",
  product_single_price: "",
  product_create_person: "",
  in_memo: ""
});
const rules = reactive({
  product_id: [{ required: true, message: "入库编号", trigger: "blur" }],
  product_name: [{ required: true, message: "产品名称", trigger: "blur" }],
  product_category: [{ required: true, message: "产品类别", trigger: "blur" }],
  product_unit: [{ required: true, message: "产品单位", trigger: "blur" }],
  product_inwarehouse_number: [
    { required: true, message: "库存数量", trigger: "blur" }
  ],
  product_single_price: [
    { required: true, message: "产品单价", trigger: "blur" }
  ],
  product_create_person: [
    { required: true, message: "入库操作人", trigger: "blur" }
  ]
});
const isEdit = ref(false);
const pageNum = ref(1);
const pageSize = ref(10);
const tableData = ref([
  {
    product_id: "1",
    product_name: "2",
    product_category: "3",
    product_unit: "4",
    product_inwarehouse_number: "5",
    product_single_price: "6",
    product_all_price: "7",
    product_status: "7",
    product_create_person: "8",
    product_create_time: "9"
  }
]);
const total = ref(0);
const account = ref();
const handleEdit = (index, row) => {
  isEdit.value = true;
  ruleForm.id = row.id;
  ruleForm.product_id = row.product_id;
  ruleForm.product_name = row.product_name;
  ruleForm.product_category = row.product_category;
  ruleForm.product_unit = row.product_unit;
  ruleForm.product_inwarehouse_number = row.product_inwarehouse_number;
  ruleForm.product_single_price = row.product_single_price;
  ruleForm.product_create_person = row.product_create_person;
  ruleForm.in_memo = row.in_memo;
  dialogVisible.value = true;
};
const handleDelete = (index, row) => {
  ElMessageBox.confirm("是否删除此产品？", "删除操作", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let query = {
        id: row.id
      };
      deleteProduct(query).then(async res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        await addOperationLog({
          operation_person: localStorage.getItem("name"),
          operation_content: "对id是" + row.id + "的产品删除",
          operation_level: "高级"
        });
        togetProduct();
        ElMessage.success(res.data.message);
      });
    })
    .catch(() => {});
};
const handleSizeChange = val => {
  pageSize.value = val;
  togetProduct();
};
const handleCurrentChange = val => {
  pageNum.value = val;
  togetProduct();
};
const product_id = ref();
const togetProduct = () => {
  let query = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    product_id: product_id.value
  };
  getProduct(query).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    tableData.value = res.data.data.list;
    total.value = res.data.data.total;
  });
};
const submitForm = async formEl => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (isEdit.value) {
        let data = {
          id: ruleForm.id,
          product_name: ruleForm.product_name,
          product_category: ruleForm.product_category,
          product_unit: ruleForm.product_unit,
          product_inwarehouse_number: ruleForm.product_inwarehouse_number,
          product_single_price: ruleForm.product_single_price,
          in_memo: ruleForm.in_memo
        };
        editProduct(data).then(async res => {
          if (res.data.status != 0) {
            return ElMessage.error(res.data.message);
          }
          await addOperationLog({
            operation_person: localStorage.getItem("name"),
            operation_content: "对id是" + ruleForm.id + "的产品修改",
            operation_level: "一般"
          });

          togetProduct();
          ElMessage.success(res.data.message);
          dialogVisible.value = false;
        });
      } else {
        addProduct(ruleForm).then(async res => {
          if (res.data.status != 0) {
            return ElMessage.error(res.data.message);
          }
          await addOperationLog({
            operation_person: localStorage.getItem("name"),
            operation_content: "添加了产品",
            operation_level: "中级"
          });

          togetProduct();
          ElMessage.success(res.data.message);
          dialogVisible.value = false;
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const dialogVisibleClose = formEl => {
  if (!formEl) return;
  formEl.resetFields();
};

const outboundForm = reactive({
  id: "",
  product_name: "",
  product_out_id: "",
  product_out_number: "",
  product_out_price: "",
  product_out_apply_person: "",
  product_out_audit_person: "",
  apply_memo: "",
  product_out_status: "同意",
  product_inwarehouse_number: "",
  product_single_price: ""
});

const outboundRules = reactive({
  product_out_id: [{ required: true, message: "出库编号", trigger: "blur" }],
  product_out_number: [
    { required: true, message: "出库数量", trigger: "blur" }
  ],
  product_out_price: [{ required: true, message: "出库价格", trigger: "blur" }],
  product_out_apply_person: [
    { required: true, message: "出库申请人", trigger: "blur" }
  ]
});
const outboundFormRef = ref();
const submitOutbound = async formEl => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      outboundForm.product_name = null;
      applyProduct(outboundForm).then(async res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        await addOperationLog({
          operation_person: localStorage.getItem("name"),
          operation_content: "对id是" + outboundForm.id + "的产品出库",
          operation_level: "高级"
        });

        togetApplyProduct();
        ElMessage.success(res.data.message);
        outboundDialogVisible.value = false;
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const outbounddialogVisibleClose = formEl => {
  if (!formEl) return;
  formEl.resetFields();
};
const outboundDialogVisible = ref(false);
const product_name = ref();
const rowInfo = ref();
const handleOutbound = (index, row) => {
  outboundForm.product_name = row.product_name;
  outboundForm.id = row.id;
  rowInfo.value = row;
  outboundDialogVisible.value = true;
};

const examineDialogVisible = ref(false);
const handleExamine = (index, row) => {
  outboundForm.id = row.id;
  outboundForm.product_out_id = row.product_out_id;
  outboundForm.product_out_number = row.product_out_number;
  outboundForm.product_out_price = row.product_out_price;
  outboundForm.product_out_apply_person = row.product_out_apply_person;
  outboundForm.product_out_audit_person = row.product_out_audit_person;
  outboundForm.apply_memo = row.apply_memo;
  outboundForm.product_inwarehouse_number = row.product_inwarehouse_number;
  outboundForm.product_single_price = row.product_single_price;

  examineDialogVisible.value = true;
};

const handleWithdraw = (index, row) => {
  ElMessageBox.confirm("是否撤回?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let query = {
        id: row.id
      };
      withdraw(query).then(async res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        await addOperationLog({
          operation_person: localStorage.getItem("name"),
          operation_content: "对id是" + row.id + "的产品撤回申请",
          operation_level: "一般"
        });

        togetProduct();
        togetApplyProduct();
        ElMessage.success(res.data.message);
      });
    })
    .catch(() => {});
};

const tableDataExamine = ref([]);
const pageNum1 = ref(1);
const pageSize1 = ref(10);
const totalExamine = ref(0);
const product_out_id = ref();
const togetApplyProduct = () => {
  let query = {
    pageNum: pageNum1.value,
    pageSize: pageSize1.value,
    product_out_id: product_out_id.value
  };
  getApplyProduct(query).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    tableDataExamine.value = res.data.data.list;
    totalExamine.value = res.data.data.total;
  });
};
const handleSizeChange1 = val => {
  pageSize1.value = val;
  togetApplyProduct();
};
const handleCurrentChange1 = val => {
  pageNum1.value = val;
  togetApplyProduct();
};

const toauditProduct = () => {
  let data = {
    id: outboundForm.id,
    product_out_status: outboundForm.product_out_status,
    product_out_id: outboundForm.product_out_id,
    product_out_number: outboundForm.product_out_number,
    product_out_price: outboundForm.product_out_price,
    product_out_apply_person: outboundForm.product_out_apply_person,
    product_audit_time: outboundForm.product_audit_time,
    product_out_audit_person: outboundForm.product_out_audit_person,
    audit_memo: outboundForm.audit_memo,
    product_inwarehouse_number: outboundForm.product_inwarehouse_number,
    product_single_price: outboundForm.product_single_price
  };
  auditProduct(data).then(async res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    await addOperationLog({
      operation_person: localStorage.getItem("name"),
      operation_content:
        "对的id是" +
        outboundForm.id +
        "产品出库" +
        outboundForm.product_out_status,
      operation_level: "中级"
    });

    togetProduct();
    togetApplyProduct();
    examineDialogVisible.value = false;
    ElMessage.success(res.data.message);
  });
};
const examineDialogVisibleClose = () => {
  outboundForm.product_out_status = "同意";
  outboundForm.product_out_audit_person = "";
  outboundForm.audit_memo = "";
};

const dynamicTags1 = ref([]);
const togetDepartment1 = () => {
  getProductType().then(res => {
    if (res.data.status != 0) {
      return;
    }
    dynamicTags1.value = res.data.data;
  });
};

//声明周期函数，自动执行初始化
onMounted(() => {
  togetProduct();
  togetApplyProduct();
  togetDepartment1();
});
</script>

<style scoped lang="scss">
.productManager {
}
.breadcrumb {
  display: flex;
  margin-bottom: 10px;
}
.content {
  background: #fff;
  .top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}
</style>